package com.example.wxy.bbtapp;


import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Toast;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.example.wxy.bbtapp.Common.ListHelper;
import com.example.wxy.bbtapp.Common.ServiceHelper;
import com.example.wxy.bbtapp.Startup.AppSettings;
import com.example.wxy.bbtapp.Startup.DbService;
import com.example.wxy.bbtapp.Common.httpCallBack;
import com.example.wxy.bbtapp.DeviceService.ScreenShotService;
import com.example.wxy.bbtapp.Models.ClassTime;
import com.example.wxy.bbtapp.Models.bindinfo;
import com.example.wxy.bbtapp.Service.BBTService;
import com.example.wxy.bbtapp.Service.BindService;

import com.example.wxy.bbtapp.Models.RetrunValue.classData;
import com.example.wxy.bbtapp.Models.RetrunValue.schoolData;
import com.example.wxy.bbtapp.Service.CourseRecordService;
import com.example.wxy.bbtapp.Service.ServiceBus;

import org.xutils.ex.DbException;

public class MainActivity extends AppCompatActivity {
    private List<String> school_list;
    private List<String> class_list;
    private List<String> basicUrl_List;
    private ArrayAdapter<String> arr_adapter;
    private ArrayAdapter<String> arr_adapter1;
    private Spinner spinner1;
    private Spinner spinner3;
    private Button loginBtn;
    public String num = "";
    public String schoolId = "";
    public String classId = "";
    public String Cook = "";
    public String basicUrl = "";
    public String basic_url = "";
    public ArrayList<schoolData.DataBean> allchool;//初始化学校的数据
    public ArrayList<classData.DataBean> allclass;
    public Button btnTest;
    public String schoolName = "";
    public String className = "";

    @Override
    protected void onResume() {

        if(getRequestedOrientation()!= ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE){
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        }

        super.onResume();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
Log.d(AppSettings.DebugTag, "Main Create");

        try
        {
            if(!ServiceHelper.isServiceRunning(MainActivity.this, "BBTServices")) {
                // 开启服务
                startService(new Intent(MainActivity.this, BBTService.class));
            }
        }
        catch (Exception E)
        {
             Log.v("TAG",E.getMessage());
        }


        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        spinner1 = (Spinner) findViewById(R.id.spinner_classRoom);
        spinner3 = (Spinner) findViewById(R.id.spinner_school);
        loginBtn = (Button) findViewById(R.id.login);
        btnTest =(Button)findViewById(R.id.btnTest);

        if (!LoadData()) {
            myApplication.bindinofs = new bindinfo();
        }
        InitData();

        //绑定的事件
        loginBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Bind();
            }
        });

btnTest.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        Test();
    }
});

        //学校的点击事件
        spinner3.setOnItemSelectedListener(
                new AdapterView.OnItemSelectedListener() {
                    public void onItemSelected(AdapterView<?> parent,
                                               View view, int position, long id) {
                        if (position == 0) {
                            return;
                        }
                        Log.d(AppSettings.DebugTag, "spinner3.setOnItemSelected");
                        schoolId = allchool.get(position).getSchool_id();
                        String Id = allchool.get(position).getSchool_id();
                        SchoolSelected(Id);
                        schoolName = allchool.get(position).getSchool_name();
                        loginBtn.setEnabled(true);

                    }

                    public void onNothingSelected(AdapterView<?> parent) {

                    }
                });
        //教室的绑定事件
        spinner1.setOnItemSelectedListener(
                new AdapterView.OnItemSelectedListener() {
                    public void onItemSelected(AdapterView<?> parent,
                                               View view, int position, long id) {
                        classId = allclass.get(position).getClass_room_id();
                        className = allclass.get(position).getClass_adjust_name();
                        Log.d(AppSettings.DebugTag, "spinner1.setOnItemSelected");
                        loginBtn.setEnabled(true);
                    }

                    public void onNothingSelected(AdapterView<?> parent) {

                    }
                });
    }

    private  boolean LoadData()
    {
        myApplication.bindinofs =BindService.LoadBindInfo();

        return myApplication.bindinofs != null;
    }

    private void InitData() {
        BindService.getCook(new httpCallBack<String>("登录"){
            @Override
            public void onSuccess(String result) {
                BindService.GetSchoolList(new httpCallBack<ArrayList<schoolData.DataBean>>("获取学校列表") {
                    @Override
                    public void onSuccess(ArrayList<schoolData.DataBean> result) {

                        Log.d(AppSettings.DebugTag, "BindService.GetSchoolList");
                        allchool = result;
                        school_list = new ArrayList<String>();
                        for (int i = 0; i < result.size(); i++) {
                            school_list.add(result.get(i).getSchool_name());
                        }
                        schoolId = result.get(0).getSchool_id();
                        schoolName = result.get(0).getSchool_name();

                        try {
                            school_list.add(0, "请选择学校");
                            schoolData.DataBean s = new schoolData.DataBean();
                            s.setSchool_name("请选择学校");
                            allchool.add(0, s);

                            //bindSchool
                            arr_adapter1 = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_item, school_list);
                            arr_adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                            spinner3.setAdapter(arr_adapter1);

                            final bindinfo bindinfo = DbService.getDB().findFirst(bindinfo.class);
                            if (bindinfo == null || bindinfo.getSchoolName() == null || bindinfo.getSchoolName().length() == 0) {
                                //Toast.makeText(MainActivity.this, "我跳到数据库无数据的", Toast.LENGTH_SHORT).show();
                            }
                            else
                            {
                                int Index = new ListHelper<schoolData.DataBean>().FindIndex(allchool, new ListHelper.Expression<schoolData.DataBean>() {
                                    @Override
                                    public boolean where(schoolData.DataBean org) {
                                        return org.getSchool_name().equals(bindinfo.getSchoolName());
                                    }
                                });

                                spinner3.setSelection(Index, true);
                                SchoolSelected(bindinfo.getSchoolID());
                            }
                        } catch (DbException e) {
                            e.printStackTrace();
                        }


                    }
                });
            }
        });

    }

    private void Test()
    {
        ServiceBus.DoEventing = true;
        ScreenShotService.ShotTest(ServiceBus.Current_CourseRecord, MainActivity.this);
        CourseRecordService.Post(ServiceBus.Current_CourseRecord);
    }

    private void Bind() {

        BindService.GetClassTime(schoolId, new httpCallBack<List<ClassTime>>("获取时间表"){
            @Override
            public void onSuccess(List<ClassTime> result) {
                super.onSuccess(result);

                Log.d(AppSettings.DebugTag, "BindService.GetClassTime");
                // 绑定到服务器
                Date date =  new Date();
                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
                String nowDate  =  df.format(new Date());// new Date()为获取当前系统时间
                BindService.SaveBindInfo(schoolName,className,schoolId,classId,nowDate,new httpCallBack<Boolean>("绑定设备"){
                    @Override
                    public void onSuccess(Boolean result) {
                        if(result){//绑定成功
                            Log.d(AppSettings.DebugTag, "BindService.SaveBindInfo onSuccess");
                            Toast.makeText(MainActivity.this, "绑定成功", Toast.LENGTH_SHORT).show();
                            MainActivity.this.finish();
                        }else{//绑定失败
                            Toast.makeText(MainActivity.this, "绑定失败，请重新绑定", Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onError(Throwable ex, boolean isOnCallback) {
                        Toast.makeText(MainActivity.this, "绑定失败，请重新绑定", Toast.LENGTH_SHORT).show();
                    }
                });
            }

        });
    }

    private void SchoolSelected(String SchoolID) {

        schoolId = SchoolID;
        BindService.GetClassList(SchoolID, new httpCallBack<ArrayList<classData.DataBean>>("获取班级"){
            @Override
            public void onSuccess(ArrayList<classData.DataBean> result) {
                super.onSuccess(result);
                allclass = result;
                class_list = new ArrayList<String>();
                for (int i = 0; i < result.size(); i++) {
                    class_list.add(result.get(i).getClass_adjust_name());
                    //allclass.add( new classData.DataBean());
                }
                try {

                    arr_adapter1 = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_item, class_list);
                    arr_adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                    spinner1.setAdapter(arr_adapter1);


                    final bindinfo bindinfo =  DbService.getDB().findFirst(bindinfo.class);
                    if(bindinfo != null && bindinfo.getClassName().length() > 0)
                        //class_list.add(0,bindinfo.getClassName());
                    {
                        int Index = new  ListHelper<classData.DataBean>().FindIndex(allclass, new ListHelper.Expression<classData.DataBean>(){
                            @Override
                            public boolean where(classData.DataBean org) {
                                return org.getClass_adjust_name().equals(bindinfo.getClassName());
                            }
                        });

                        spinner1.setSelection(Index,true);
                    }
                } catch (DbException e) {
                    e.printStackTrace();
                }

            }
        });
    }
}
